package com.sh.cathtml.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sh.suhe.utildemos.R
import com.sh.suhe.utildemos.model.MainModel
import java.util.ArrayList

class CatalogueAdapter: RecyclerView.Adapter<CatalogueAdapter.ViewHolder>() {
    var datas = ArrayList<MainModel>()
    lateinit var onClick:OnClick
    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CatalogueAdapter.ViewHolder {
        val view = LayoutInflater.from(p0.context).inflate(R.layout.adapter_main_item,null)
        return CatalogueAdapter.ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(p0: CatalogueAdapter.ViewHolder, p1: Int) {
         p0.updateData(datas[p1],onClick)
    }

    class ViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        private val title:TextView = itemView.findViewById(R.id.main_item_title)
        fun updateData(data:MainModel,onClick: OnClick){
            title.text = data.title
            title.setOnClickListener { onClick.toArticle(data) }
        }
    }
    fun notifyDataSetChanged(datas:List<MainModel> ){
        if ( datas.isNotEmpty()){

            this.datas.addAll(datas)
            notifyDataSetChanged()
        }
    }
    interface OnClick{
        fun toArticle(item: MainModel)
    }
}